<template>
  <view class="content">
    <view class="header">
      <image src="https://oss.seenlove.com/images/96f6e3633cf38776266b86636d1e2543.png" mode="widthFix" />
    </view>

    <view class="bold textCenter name">发票开具</view>
    <view class="form">
      <uv-form labelPosition="top" :model="model" :rules="rules" ref="form" labelWidth="120">
        <view class="item">
          <view class="bold fz16 title">订单号</view>
          <uv-form-item label="订单号" prop="transaction_id" required>
            <uv-input v-model="model.transaction_id" placeholder="请输入" @input="outTradeNoInfo"></uv-input>
          </uv-form-item>
          <uv-form-item label="开票金额" v-if="orderInfo.amount && orderInfo.amount.payer_total">
            {{ orderInfo.amount.payer_total / 100 }}
          </uv-form-item>
          <uv-form-item label="支付状态" v-if="orderInfo.amount && orderInfo.amount.payer_total">
            {{ orderInfo.trade_state_desc }}
          </uv-form-item>
        </view>

        <view class="item">
          <view class="bold fz16 title">开票商品</view>
          <uv-form-item label="商品名称">
            <pickerCom v-model="model.spmc" :columns="[dicts]" keyName="dict_label" keyVal="dict_code" showBorder="1" placeholder="请选择商品名称">
            </pickerCom>
          </uv-form-item>
        </view>

        <view class="item">
          <view class="bold fz16 title">发票抬头信息</view>
          <uv-form-item label="公司名称" prop="name" required>
            <uv-input v-model="model.name" placeholder="请输入" @input="searchCompany">
              <template v-slot:suffix>
                <uv-icon name="weixin-fill" color="#10D269" size="25" @click="wxClick"></uv-icon>
              </template>
            </uv-input>
          </uv-form-item>
          <view class="list fz14" v-if="relatedCompanies.length">
            <view class="box" v-for="item in relatedCompanies" :key="item.nsrsbh" @click="companiesClick(item)">
              <view class="qymc">公司名：{{ item.qymc }}</view>
              <view>税号：{{ item.nsrsbh }}</view>
            </view>
          </view>

          <uv-form-item label="公司税号">
            <uv-input v-model="model.taxNo" placeholder="请输入" disabled></uv-input>
          </uv-form-item>
        </view>

        <view class="item">
          <view class="bold fz16 title">发票接收方式</view>
          <uv-form-item label="邮箱地址" prop="email">
            <uv-input v-model="model.email" placeholder="请输入"></uv-input>
          </uv-form-item>
          <uv-form-item label="手机号码" prop="gmfMobile">
            <uv-input v-model="model.gmfMobile" placeholder="请输入"></uv-input>
          </uv-form-item>
          <!-- <uv-form-item label="备注">
            <uv-textarea v-model="model.remark" placeholder="请输入..." count autoHeight maxlength="70"></uv-textarea>
          </uv-form-item> -->
        </view>

        <view class="item">
          <uv-button text="提 交" @click="submit" :loading="loading" color="#4196A2"></uv-button>
        </view>
      </uv-form>
    </view>

  </view>
</template>

<script setup lang="ts">
import pickerCom from "@/components/uv/uvPicker.vue";
const { proxy } = getCurrentInstance();
import wechat from "@/utils/wechat.js";
const instance = getCurrentInstance();
let model = ref({
  transaction_id: "",
  name: "",
  taxNo: "",
  email: "",
  amount: null,
  remark: "",
  spmc: "",
  gmfMobile: "",
});
let timer = null; //轮询
let rules = ref({
  transaction_id: {
    type: "string",
    required: true,
    message: "请填写订单号",
    trigger: ["blur", "change"],
  },
  name: {
    type: "string",
    required: true,
    message: "请填写公司名称",
    trigger: ["blur", "change"],
  },
  gmfMobile: [
    {
      // 自定义验证函数，见上说明，注意这里面的逻辑不能出现语法报错，否则可能导致不验证
      validator: (rule, value, callback) => {
        if (value) return proxy.$utils.isPoneAvailable(value);
      },
      message: "电话号码格式错误",
      trigger: ["blur"],
    },
  ],
  email: [
    {
      // 自定义验证函数，见上说明，注意这里面的逻辑不能出现语法报错，否则可能导致不验证
      validator: (rule, value, callback) => {
        if (value) return proxy.$utils.isValidEmail(value);
      },
      message: "邮箱格式错误",
      trigger: ["blur"],
    },
  ],
});
let loading = ref(false);
let orderInfo = ref({});
let relatedCompanies = ref([]); //相关公司
let dicts = ref([]);

onShow(() => {
  navTitle();
  getDict();
});

onUnload(() => {
  clearIntervalFunc();
});

onHide(() => {
  clearIntervalFunc();
});

let getDict = async () => {
  dicts.value = await proxy.$apis.getDict({
    type: "query",
    data: {
      code: "billing_type ",
    },
  });
};

function init() {
  model.value = {
    transaction_id: "",
    name: "",
    taxNo: "",
    email: "",
    amount: null,
    remark: "",
    spmc: "",
    gmfMobile: "",
  };
  instance.refs.form.resetFields();
}

function navTitle() {
  // #ifdef H5
  let navTitle = document.getElementsByTagName("uni-page-head");
  if (navTitle && navTitle.length) {
    navTitle[0].style.display = "none";
  }
  // #endif
}
let outTradeNoInfo = async (e) => {
  if (!e) return;
  try {
    orderInfo.value = await proxy.$apis.payQuery({ taxNo: e });
    model.value.amount = orderInfo.value.amount.payer_total / 100;
  } catch (error) {
    orderInfo.value = {};
    model.value.amount = 0;
  }
};
let wxClick = async () => {
  if (!proxy.$utils.isWeiXin())
    return proxy.$utils.showToast("请在微信环境里面打开", 0);
  let resp = await wechat.chooseInvoiceTitle();
  if (resp.title && resp.taxNumber) {
    model.value.name = resp.title;
    model.value.taxNo = resp.taxNumber;
  }
};
let submit = async () => {
  if (!model.value.email && !model.value.gmfMobile)
    return proxy.$utils.showToast("邮箱和手机号请选填一个");
  if (orderInfo.value.trade_state != "SUCCESS")
    return proxy.$utils.showToast("当前订单状态不支持开票");
  instance.refs.form
    .validate()
    .then((res) => {
      save();
    })
    .catch((error) => {});
};

let searchCompany = async (e) => {
  relatedCompanies.value = await proxy.$apis.autoMatchCompany({
    key: e,
  });
};

let companiesClick = (e) => {
  model.value.name = e.qymc;
  model.value.taxNo = e.nsrsbh;
  relatedCompanies.value = [];
};

let save = async () => {
  try {
    loading.value = true;
    uni.showLoading({
      title: "发票开具中",
    });
    await proxy.$apis.applyInvoice({
      data: model.value,
      type: "add",
    });
    timer = setInterval(fetchData, 1000); // 每1秒轮询一次
  } catch (error) {
  } finally {
    loading.value = false;
  }
};

const fetchData = async () => {
  let resp = await proxy.$apis.queryOrder({
    ddlsh: model.value.transaction_id,
  });
  if (resp.hasOwnProperty("status") && ![0, 1].includes(resp.status)) {
    uni.hideLoading();
    proxy.$utils.showToast(resp._status);
    clearIntervalFunc();
  }
};

let clearIntervalFunc = () => {
  clearInterval(timer);
  timer = null;
};
</script>

<style lang="scss">
page {
  background: linear-gradient(to bottom, #6f9ac4, #4196a2);
}
</style>

<style lang="scss" scoped>
.content {
  padding: 15px;
  background-color: white;
  width: calc(100% - 60px);
  margin: 25px auto 0;
  border-radius: 5px;
}

.name {
  font-size: 22px;
  color: #4196a2;
  padding: 25px 0;
}

.item {
  background-color: white;
  padding: 15px;

  .title {
    margin-bottom: 8px;
  }
}

.list {
  .box {
    border-bottom: 0.5px solid #f3f4f7;
    padding: 10px 0;

    .qymc {
      margin-bottom: 5px;
    }
  }
}
</style>
